<?php

Loader::using(array(
    "ext::libs::phpUI::UIControl",
    "ext::libs::phpUI::factories::BaseUIControlFactory",
    "ext::libs::inscripcionesGenericas::filters::*",
    "models::entities::CamposFormularios",
    "ext::libs::phpUI::impl::jQuery::constraints::*",
    "ext::libs::phpUI::impl::jQuery::controls::*",
));

class QuestionBasedUIControlFactory extends BaseUIControlFactory {

    /**
     *
     * @var CamposFormularios
     */
    private $question;

    /**
     *
     * @var QuestionBasedUIControlFactory
     */
    private static $defaultInstance;

    function __construct() {
        parent::setFilters(array(
            new BasicUIControlFilter(),
            new BasicDataSetUIControlFilter(),
            new DataSourceDataSetUIControlFilter(),
            new ConstraintUIControlFilter(),
            new DependencyUIControlFilter(),
        ));
    }

    protected function makeInstance() {
        QuestionBasedUIControlFilter::setQuestion($this->question);
        
        $typeParts = explode("-", strtolower($this->question->getTipo()));
        $type = "";
        
        foreach ($typeParts as $part) {
            $type .= ucwords($part);
        }

        $control = null;
        if (class_exists($type) && array_search("UIControl", class_parents($type))) {
            $control = new $type();
        }else{
            $control = new Text();
            $control->addStyleClass("set-as-default-type-for-$type");
        }
        
        $this->setBasicInfo($control);

        return $control;
    }

    protected function setBasicInfo(UIControl &$control) {
        $control->setId($this->question->getId());
        $control->setName("Values[{$this->question->getId()}]");
        $control->setRequired($this->question->getRequired());
    }

    public function getQuestion() {
        return $this->question;
    }

    public function setQuestion(CamposFormularios $question) {
        $this->question = $question;
    }

    /**
     *
     * @return QuestionBasedUIControlFactory
     */
    public static function instance() {
        if (self::$defaultInstance == NULL) {
            self::$defaultInstance = new QuestionBasedUIControlFactory();
        }

        return self::$defaultInstance;
    }

}

?>
